#!/bin/bash

brokerListFile=./data/broker.list
nodeListFile=./data/node.list
doLabelShell=./output/labelNodes.sh
dxcServerDeployTemplate=./template/dxc-server-deploy-template.yaml
outputDir=./output
envFile=./data/env.cfg

#0.source env file && mkdir dir
source $envFile
mkdir -p ./output

#1.get all solace broker list
n=0;
while read line;
do
    [[ $line = \#* ]] && continue
    echo "broker info:$line"
    brokerList[$n]=`echo "$line" | awk '{print $1}'`
    brokerVPNList[$n]=`echo "$line" | awk '{print $2}'`
    brokerUserList[$n]=`echo "$line" | awk '{print $3}'`
    brokerPasswordList[$n]=`echo $line | awk '{print $4}'`
    ((n++));
done<$brokerListFile
brokerListLength=${#brokerList[@]}
echo "broker number:" "$brokerListLength"

#2.get all node list
n=0;while read line;do nodeList[$n]=$line;((n++));done<$nodeListFile
nodeListLength=${#nodeList[@]}
echo "node number:" "$nodeListLength"

#3.calculate the node number of each group
residue=$(($nodeListLength%$brokerListLength))
quotient=$(($nodeListLength/$brokerListLength))

echo "quotient:" $quotient "residue:" $residue

rm -fr ./output/*

start=0
end=0
for ((groupIndex=0; groupIndex < brokerListLength; groupIndex++));
do
    groupName=group$groupIndex
    end=$(($start + $quotient - 1))
    if [[ $groupIndex < $residue ]];then
      end=$(($end + 1))
    fi
    pickedNodeList=${nodeList[@]:$start:$(($end - $start + 1))}
    echo "groupIndex:" $groupIndex "start:" $start "end:" $end "broker info" ${brokerList[$groupIndex]} "node list:" $pickedNodeList
    for ((i=$start; i <= $end; i++));
    do
        echo "kubectl label nodes ${nodeList[$i]} dxc_server_group=$groupName --overwrite=true" >> $doLabelShell
    done
    echo "" >> $doLabelShell
    
    sed -e "s/GROUP_NAME/$groupName/g" \
        -e "s/APP_AZ/$APP_AZ/g" \
        -e "s/APP_ORG/$APP_ORG/g" \
        -e "s/APP_SU/$APP_SU/g" \
        -e "s/BROKER_VPN/${brokerVPNList[$groupIndex]}/g" \
        -e "s/BROKER_HOST/${brokerList[$groupIndex]}/g" \
        -e "s/BROKER_USERNAME/${brokerUserList[$groupIndex]}/g" \
        -e "s/BROKER_PASSWORD/${brokerPasswordList[$groupIndex]}/g " \
        -e "s/APP_WKS/$APP_WKS/g" \
        -e "s/APP_ENV/$APP_ENV/g" \
        -e "s/REPOSITORY_TYPE/$REPOSITORY_TYPE/g" \
        -e "s/CACHE_LAUNCH_TYPE/$CACHE_LAUNCH_TYPE/g" \
        -e "s/CACHE_ADDR_FOR_REDIS/$CACHE_ADDR_FOR_REDIS/g" \
        -e "s/CACHE_PASSWORD_FOR_REDIS/$CACHE_PASSWORD_FOR_REDIS/g" \
        -e "s/CACHE_ADDR_FOR_HAZELCAST/$CACHE_ADDR_FOR_HAZELCAST/g" \
         $dxcServerDeployTemplate  >$outputDir/dxc-server-$groupName.yaml

    start=$(($end + 1))
done

chmod 755 $doLabelShell
